package com.nazca.tvremote.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.nazca.tvremote.util.RLog;

public class EventSender {

	private static final String TAG = "EventSender";
	
	private Socket mSocket;
	private String mDstAddress;
	private int mDstPort;
	private PrintWriter mPrintWriter;
	
	private static EventSender sInstance;
	
	public static EventSender getInstance(String dstAddress, int dstPort){
		if(sInstance != null){
			sInstance.close();
		}
		sInstance = new EventSender(dstAddress, dstPort);
		return sInstance;
	}
	
	private EventSender(){
	}

	private EventSender(String dstAddress, int dstPort){
		RLog.d(TAG, "EventSender");
		mDstAddress = dstAddress;
		mDstPort = dstPort;
		mSocket = new Socket();
	}
	public void println(String str){
//		connect();8
		mPrintWriter.println(str);
//		PrintWriter out;
//		try {
//			out = new PrintWriter(mSocket.getOutputStream(), true);
//			out.print(str);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		while(!keeplive());
	}
	
	public boolean close(){
		RLog.d(TAG, "close()");
//		if(mPrintWriter != null){
//			mPrintWriter.close();
//			mPrintWriter = null;
//		}
		if(mSocket != null){
			try {
				mSocket.close();
				mSocket = null;
				return true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		sInstance = null;
		return false;
	}
	
	public boolean connect(){
		RLog.d(TAG, "connect()");
		try {
//			if (mSocket == null || !(mSocket.isConnected() && !mSocket.isClosed())) {
//				RLog.d(TAG, "if (mSocket == null || !(mSocket.isConnected() && !mSocket.isClosed())))");
//				mSocket = new Socket(mDstAddress, mDstPort);
//				mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
//				mSocket.setKeepAlive(true);
//			}
			if (mSocket != null && !mSocket.isConnected()) {
			    RLog.d(TAG, "new InetSocketAddress()");
				mSocket.connect(new InetSocketAddress(mDstAddress, mDstPort));
				mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
				mSocket.setKeepAlive(true);
			}
			return true;
		} /*catch (UnknownHostException e) {
			e.printStackTrace();
		} */catch (IOException e) {
			e.printStackTrace();
//			if(mPrintWriter != null){
//				mPrintWriter.close();
//				mPrintWriter = null;
//			}
//			if(mSocket != null){
//				try {
//					mSocket.close();
//				} catch (IOException e1) {
//					e1.printStackTrace();
//				}
//				mSocket = null;
//			}
		} 
		return false;
	}
}
